<template>
  <base-breadcrumb>
    <searchData
      :search-data="searchArr"
      @search="search"
    />
    <a-card :bordered="false">
      <!-- <title-name title="固定资产台账" /> -->

      <!-- <div class="table-operator">
        <div class="pub-table-action-btn">
          <a-button
            slot="excelBtn"
            type="primary"
            @click="exportSelect"
          >
            导出选中
          </a-button>
          <a-button
            slot="excelBtn"
            type="primary"
            @click="exportAll"
          >
            导出全部
          </a-button>
        </div>
      </div> -->
      <list-table
        ref="table"
        row-key="id"
        :columns="columns"
        :request="loadData"
        :alert="true"
        show-size-changer
        show-quick-jumper
        :export-config="{ use: true, select: '固定资产台账', all: '固定资产台账' }"
      >
        <span
          slot="index"
          slot-scope="text, record, index"
        >{{ index + 1 }}</span>
        <template
          slot="assetCode"
          slot-scope="text"
        >
          <span v-if="text">{{ text }}</span>
          <span
            v-else
            style="color: red;"
          >未填写</span>
        </template>
        <template
          slot="operation"
          slot-scope="text, record"
        >
          <MoreButton>
            <a @click="$nav('add',{id:record.id,detail:1})">查看</a>
            <a
              v-if="record.parameterStatus !== 4 && record.keeptorId === $userInfo().id"
              @click="form = $assign(form,record);modal.edit = true"
            >编辑</a>
            <a
              v-if="(!record.assetCode) && record.keeptorId === $userInfo().id"
              @click="form = $assign(form,record);modal.code = true "
            >填写资产编号</a>
            <a
              v-if="record.statusStr !== '已处置' && record.keeptorId === $userInfo().id"
              @click="form = $assign(form,record);modal.dispose = true"
            >处置</a>
          </MoreButton>
        </template>
      </list-table>
      <!-- <pagination
        v-model="pageNo"
        :total="totalSize"
        :page-size.sync="pageSize"
        @change="handlePageChange"
        @showSizeChange="showSizeChange"
      /> -->
    </a-card>
    <a-modal
      title="编辑"
      :visible="modal.edit"
      :confirm-loading="modal.loading"
      class="normal-modal"
      ok-text="提交"
      @cancel="cancel(modal.edit = false)"
      @ok="editItem"
    >
      <div class="page-detail">
        <BForm
          ref="bform1"
          :rule="rules2"
          :form="form"
          :config="editForm"
        />
      </div>
    </a-modal>
    <a-modal
      title="填写资产编号"
      :visible="modal.code"
      :confirm-loading="modal.loading"
      class="normal-modal"
      ok-text="提交"
      @cancel="cancel(modal.code = false)"
      @ok="editCode"
    >
      <div class="page-detail">
        <BForm
          ref="bform2"
          :form="form"
          :rule="rules"
          :config="codeForm"
        />
      </div>
    </a-modal>
    <a-modal
      title="处置"
      :visible="modal.dispose"
      :confirm-loading="modal.loading"
      class="normal-modal"
      ok-text="提交"
      @cancel="cancel(modal.dispose = false)"
      @ok="editDispose"
    >
      <div
        v-loading="modal.loading"
        class="page-detail"
      >
        <BForm
          ref="bform3"
          :form="form"
          :rule="rules2"
          :config="disposeForm"
        />
      </div>
    </a-modal>
  </base-breadcrumb>
</template>

<script>
import assetApi from '@/api/office/asset'
import SelectCompanyAndProject from '@/components/Select/SelectCompanyAndProject'
import SelectOrgDepartment from '@/components/Select/SelectOrgDepartment'
import BSelect from '@/components/BComponents/BSelect'
import SelectOrgPeople from '@/components/Select/SelectOrgPeople'
import BUploadVModel from '@/components/BComponents/BUploadVModel'
import OrgTreeSelect from '@/components/OrgTreeSelect'

export default {
  name: 'AssetManagementListIndex',
  data() {
    return {
      loading: false,
      pageNo: 1,
      pageSize: 10,
      totalSize: 0,
      selectedRowKeys: [],
      tableData: [],
      form: {
        disposalId: this.$userInfo().id,
        disposalName: this.$userInfo().name,
        keepDepId: '',
        status: '',
        keeptorId: '',
        disposalTime: '',
        assetDisposalFiles: [],
        assetDisposalApplyFiles: [],
        assetAuthenticateFiles: [],
        assetDisposalPhotoFiles: []
      },
      modal: {
        loading: false,
        edit: false,
        code: false,
        dispose: false
      },
      rowId: '',
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          scopedSlots: { customRender: 'index' }
        },
        {
          title: '资产编号',
          dataIndex: 'assetCode',
          scopedSlots: { customRender: 'assetCode' },
          width: 150
        },
        {
          title: '资产名称',
          dataIndex: 'assetName',
          width: 120
        },
        {
          title: '资产类别',
          dataIndex: 'assetSpeciesStr',
          width: 150
        },
        {
          title: '单位',
          dataIndex: 'unit',
          width: 150
        },
        {
          title: '原值(元)',
          dataIndex: 'originalValue',
          width: 100
        },
        {
          title: '使用年限(年)',
          dataIndex: 'durableYears',
          width: 120
        },
        {
          title: '保管单位',
          dataIndex: 'keepUnitName',
          width: 170
        },
        {
          title: '保管部门',
          dataIndex: 'keepDepName',
          width: 170
        },
        {
          title: '保管人',
          dataIndex: 'keeptorName',
          width: 170
        },
        {
          title: '验收/竣工/起用日期',
          dataIndex: 'time',
          width: 170
        },
        {
          title: '折旧年限(月)',
          dataIndex: 'discountMonth',
          width: 150
        },
        {
          title: '已提折旧(元)',
          dataIndex: 'discountMoney',
          width: 150
        },
        {
          title: '净值(元)',
          dataIndex: 'netValue',
          width: 150
        },
        {
          title: '残值(元)',
          dataIndex: 'salvageValue',
          width: 150
        },
        {
          title: '状态',
          dataIndex: 'statusStr',
          width: 150
        },
        {
          title: '操作',
          width: 250,
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      loadData: (parameter) => {
          const requestParameters = Object.assign({}, parameter, { query: this.queryParam })
          return  assetApi.getPageParameter(requestParameters).then((res) => {
              return res
          })
      }, // 加载数据方法 必须为 Promise 对象

      searchArr: [
        // 搜索框
        {
          name: '保管单位',
          valueKey: 'searchQuery',
          type: OrgTreeSelect,
          attrs: {
            isAutoSelectFirst: true,
            isNeedOrgId:true
          }
        },
        // {
        //   name: '保管单位',
        //   type: SelectCompanyAndProject,
        //   valueKey: 'keepUnitId',
        //   isAuth: false,
        //   isAutoSelectMe: true
        // },
        {
          name: '保管部门',
          valueKey: 'keepDepId',
          keyValue: 'searchQuery._checked',
          type: SelectOrgDepartment,
          isAutoSelectMe: true,
          isOrgIdNotNull: true,
          isSearch: true
        },
        {
          name: '保管人',
          value: 'keeptorName',
          type: 'input'
        },
        {
          name: '资产名称',
          value: 'assetName',
          type: 'input'
        },
        {
          name: '资产类别',
          valueKey: 'assetSpecies',
          type: BSelect,
          data: [],
          request: () => assetApi.typesLabel({ type: 18 })
        },
        {
          name: '资产编号',
          value: 'assetCode',
          type: 'input'
        },
        {
          name: '状态',
          value: 'parameterStatus',
          type: 'select',
          data: [
            { label: '正在使用', value: 2 },
            { label: '闲置', value: 3 },
            { label: '已处置', value: 4 }
          ]
        }
      ],
      queryParam: {
        searchQuery: { _checked: this.$currentPost().id, },
        keepUnitId: this.$currentPost().id,
        keepDepId: this.$currentPost().deptId
      },
      rules: {
        assetCode: { required: true, message: '资产编号不能为空', trigger: 'change' }
      },
      rules2: {
        status: { required: true, message: '资产状态不能为空', trigger: 'change' },
        keeptorId: { required: true, message: '保管人不能为空', trigger: 'change' },
        disposalTime: { required: true, message: '处置日期不能为空', trigger: 'change' },
        assetDisposalFiles: { type: 'array', required: true, message: '请上传处置报告', trigger: 'change' },
        assetDisposalApplyFiles: { type: 'array', required: true, message: '请上传处置申请表', trigger: 'change' },
        assetAuthenticateFiles: { type: 'array', required: true, message: '请上传第三方鉴定书', trigger: 'change' },
        assetDisposalPhotoFiles: { type: 'array', required: true, message: '请上传处置资产照片', trigger: 'change' }
      },
      pathName: this.$route.path
    }
  },
  computed: {
    //eslint-disable-next-line vue/no-side-effects-in-computed-properties
    editForm() {
      return [
        {
          row: true,
          children: [
            {
              type: 'input', value: 'assetCode', label: '资产编号', colSpan: 12,
              attrs: { disabled: true, placeholder: '' }
            },
            { type: 'input', value: 'assetName', label: '资产名称', colSpan: 12, attrs: { disabled: true } },
            {
              type: 'select', value: 'parameterStatus', label: '资产状态', colSpan: 12,
              attrs: {
                data: [
                  // { name: '已提交', id: 1 },
                  { name: '正在使用', id: 2 },
                  { name: '闲置', id: 3 }
                  // { name: '已处置', id: 4 }
                ]
              }
            },
            { type: 'input', value: 'keepUnitName', label: '保管单位', colSpan: 12, attrs: { disabled: true } },
            { type: 'input', value: 'keepDepName', label: '保管部门', colSpan: 12, attrs: { disabled: true } },
            {
              type: SelectOrgPeople, colSpan: 12,
              value: 'keeptorId',
              label: '保管人',
              attrs: {
                orgId: this.form.keepDepId,
                isOrgIdNotNull: true,
                init: true,
                isAutoSelectMe: true
              },
              on: {
                //eslint-disable-next-line
                onSelectChange: (e) => this.form.keeptorName = e.name
              }
            }
          ]
        }
      ]
    },
    codeForm() {
      return [
        {
          row: true,
          children: [
            { type: 'input', value: 'assetCode', label: '资产编号', colSpan: 12, attrs: { placeholder: '' } },
            { type: 'number', value: 'assetName', label: '资产名称', colSpan: 12, attrs: { disabled: true } }
          ]
        }
      ]
    },
    disposeForm() {
      return [
        {
          row: true,
          children: [
            {
              type: 'number', value: 'assetCode', label: '资产编号', colSpan: 12,
              attrs: { disabled: true, placeholder: '' }
            },
            { type: 'number', value: 'assetName', label: '资产名称', colSpan: 12, attrs: { disabled: true } },
            { type: 'number', value: 'disposalName', label: '处置人', colSpan: 12, attrs: { disabled: true } },
            { type: 'date-picker', value: 'disposalTime', label: '处置日期', colSpan: 12 },
            {
              type: BUploadVModel, value: 'assetDisposalFiles', label: '处置报告', colSpan: 24,
              attrs: { businessCode: 'UN09', uploadType: 'single' }
            },
            {
              type: BUploadVModel, value: 'assetDisposalApplyFiles', label: '处置申请表', colSpan: 24,
              attrs: { businessCode: 'UN09', uploadType: 'single' }
            },
            {
              type: BUploadVModel, value: 'assetAuthenticateFiles', label: '第三方鉴定书', colSpan: 24,
              attrs: { businessCode: 'UN09', uploadType: 'single' }
            },
            {
              type: BUploadVModel, value: 'assetDisposalPhotoFiles', label: '处置资产照片', colSpan: 24,
              attrs: { businessCode: 'UN09', uploadType: 'image-list' }
            }
          ]
        }
      ]
    }
  },
  created: function() {
    // this.list()
  },
  mounted: function() {
    console.log('mounted-----------table的Path', this.pathName)
    // 监听详情页返回刷新列表
    //this.pathName取的值是this.$route.path
    this.$bus.$on('handleRefresh' + this.pathName, () => {
      console.log('--------------------收到了，刷新刷新刷新----------------', this.pathName)
      // this.list()
      this.$refs.table.refresh(true)
    })
  },
  beforeDestroy() {
    console.log('beforeDestroy-------table的Path', this.pathName)
    this.$bus.$off('handleRefresh' + this.pathName)
  },
  methods: {
    async editCode() {
      this.$refs.bform2.validate(async valid => {
        if (valid) {
          this.$submitConfirm(async () => {
            this.modal.loading = true
            let res = await assetApi.updateparameter(this.form)
            this.modal.loading = false
            if (res.code === this.SUCCESS_CODE) {
              this.$noticeSuccess('提交成功')
              this.modal.code = false
              this.cancel()
              this.search(this.queryParam)
            }
          }, '请确认是否提交，提交后不可修改')
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    async editItem() {
      this.$refs.bform1.validate(async valid => {
        if (valid) {
          //bug2826，我他妈来回改了两次了
          this.modal.loading = true
          let res = await assetApi.updateparameter(this.form)
          this.modal.loading = false
          if (res.code === this.SUCCESS_CODE) {
            this.$noticeSuccess('提交成功')
            this.modal.edit = false
            this.cancel()
            this.search(this.queryParam)
          }
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    async editDispose() {
      this.$refs.bform3.validate(async valid => {
        if (valid) {
          this.$submitConfirm(async () => {
            this.modal.loading = true
            this.form.baseId = this.form.id
            delete this.form.id
            let res = await assetApi.insertSelective(this.form)
            this.modal.loading = false
            if (res.code === this.SUCCESS_CODE) {
              this.$noticeSuccess('提交成功')
              this.modal.dispose = false
              this.cancel()
              this.search(this.queryParam)
            }
          }, '请确认是否提交，提交后不可修改')
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })

    },
    cancel() {
      let keys = Object.keys(this.$refs)
      keys.map(v => {
        if (v.includes('bform')) {
          this.$refs[v].clearValidate()
          this.$refs[v].resetFields()
        }
      })
      this.form.keepDepId = ''
      this.form.assetCode = ''
      this.form.status = ''
      this.form.keeptorId = ''
      this.form.disposalTime = ''
      this.form.assetDisposalFiles = []
      this.form.assetDisposalApplyFiles = []
      this.form.assetAuthenticateFiles = []
      this.form.assetDisposalPhotoFiles = []
    },
    async exportSelect() {
      if (this.selectedRowKeys.length > 0) {
        return await assetApi.export({
          pageSize: this.totalSize,
          pageNo: 1,
          query: { exportIds: this.selectedRowKeys, ...this.queryParam }
        })
        if (!this.queryParam.assetSpecies) {
          await assetApi.exportExamPlanMember({
            pageSize: this.totalSize,
            pageNo: 1,
            ids: this.selectedRowKeys
          })
          await assetApi.exportExamPlanMemberCar({
            pageSize: this.totalSize,
            pageNo: 1,
            ids: this.selectedRowKeys
          })
          await assetApi.exportExamPlanMemberHouse({
            pageSize: this.totalSize,
            pageNo: 1,
            ids: this.selectedRowKeys
          })
          await assetApi.exportExamPlanMemberLow({
            pageSize: this.totalSize,
            pageNo: 1,
            ids: this.selectedRowKeys
          })
        } else {
          //固定资产
          if (this.queryParam.assetSpecies === '605004528177254571') {
            await assetApi.exportExamPlanMember({
              pageSize: this.totalSize,
              pageNo: 1,
              ids: this.selectedRowKeys
            })
            await assetApi.exportExamPlanMemberCar({
              pageSize: this.totalSize,
              pageNo: 1,
              ids: this.selectedRowKeys
            })
            await assetApi.exportExamPlanMemberHouse({
              pageSize: this.totalSize,
              pageNo: 1,
              ids: this.selectedRowKeys
            })
            //低值易耗品导出
          } else if (this.queryParam.assetSpecies === '605004528177254572') {
            await assetApi.exportExamPlanMemberLow({
              pageSize: this.totalSize,
              pageNo: 1,
              ids: this.selectedRowKeys
            })
          }
        }
      } else {
        this.$message.warning('请选择需要导出的数据')
      }
    },
    async exportAll() {
      if (this.totalSize) {
        return await assetApi.export({
          pageSize: this.totalSize,
          pageNo: 1,
          query: this.queryParam
        })
        if (!this.queryParam.assetSpecies) {
          await assetApi.exportExamPlanMember({ pageSize: this.totalSize, pageNo: 1, ...this.queryParam })
          await assetApi.exportExamPlanMemberCar({ pageSize: this.totalSize, pageNo: 1, ...this.queryParam })
          await assetApi.exportExamPlanMemberHouse({
            pageSize: this.totalSize,
            pageNo: 1, ...this.queryParam
          })
          await assetApi.exportExamPlanMemberLow({ pageSize: this.totalSize, pageNo: 1, ...this.queryParam })
        } else {
          //固定资产
          if (this.queryParam.assetSpecies === '605004528177254571') {
            await assetApi.exportExamPlanMember({ pageSize: this.totalSize, pageNo: 1, ...this.queryParam })
            await assetApi.exportExamPlanMemberCar({
              pageSize: this.totalSize,
              pageNo: 1, ...this.queryParam
            })
            await assetApi.exportExamPlanMemberHouse({
              pageSize: this.totalSize,
              pageNo: 1, ...this.queryParam
            })

            //低值易耗品导出
          } else if (this.queryParam.assetSpecies === '605004528177254572') {
            await assetApi.exportExamPlanMemberLow({
              pageSize: this.totalSize,
              pageNo: 1, ...this.queryParam
            })
          }
        }
      } else {
        this.$message.warning('没有可导出的数据')
      }
    },
    async list(callback) {
      let searchData = {
        pageSize: callback ? this.totalSize : this.pageSize,
        pageNo: this.pageNo,
        query: this.queryParam
      }
      this.loading = true
      let res = await assetApi.getPageParameter(searchData)
      this.loading = false
      if (res.code === 200) {
        this.tableData = res.data
        this.totalSize = res.totalSize
      }
    },
    search(val) {
      this.queryParam = val
      // this.pageNo = 1
      // this.list()
      this.$refs.table.refresh(true)
    },
    handlePageChange(pageNo, pageSize) {
      this.pageNo = pageNo
      this.list()
      this.selectedRowKeys = []
    },
    showSizeChange(pageNo, pageSize) {
      this.pageNo = 1
      this.pageSize = pageSize
      this.list()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    }
  }
}
</script>
